//
//  EngineMannager.m
//  BizLeader
//
//  Created by Draven on 2018/1/17.
//  Copyright © 2018年 biz. All rights reserved.
//

#import "EngineMannager.h"
#import "ConfigurationManager.h"
#import "ColorInlineConstant.h"

@implementation EngineMannager
- (void)startRequestWithRetClass:(Class)retClass andCompleteBlock:(HttpRequestCompleteBlock)completeBlock {
    self->_completeBlock = completeBlock;
    self->_retClass = retClass;

    [CoreEngine requestWithRequestType:_requestType urlString:[self generateURLHeader] paraments:[self _paramDict] completeBlock:^(id  _Nullable data, NSError * _Nullable error) {
        
        
        if (error) {
            
            //请求失败
            if ((error
                 && [error.domain isEqualToString:AFURLRequestSerializationErrorDomain]) || error.code == -1005 || error.code == NSURLErrorNotConnectedToInternet) {
                NSString *title = @"您的网络异常，请稍后尝试";
                if (error.code == NSURLErrorNetworkConnectionLost) {
                    title = @"您的网络异常，请稍后尝试";
                } else if (error.code == NSURLErrorTimedOut) {
                    title = @"您的网络异常，请稍后尝试";
                }
                title = [NSString stringWithFormat:@"%@\n错误代码(%ld)", title, error.code];
                error = [NSError errorWithDomain:AFURLRequestSerializationErrorDomain code:error.code userInfo:@{NSLocalizedDescriptionKey:title}];
            }
            if(error.code == NSURLErrorBadServerResponse) {
                ShowMessage(@"无效的地址");
            }
            self->_completeBlock(nil, error);
        } else {
            //请求成功
            NSString *json = [NSObject convertToObject:data];
            [self dealWithResponseJson:json];
        }
    }];
    
}
#pragma mark - private

- (NSString *)generateURLHeader {
    NSString *url = @"";
    if([self.path isEqualToString:@"/api/v1/users/actions/login"]) {
        url = [ConfigurationManager sharedInstance].login;
    } else {
        url = [ConfigurationManager sharedInstance].url;
    }
    url = [url stringByAppendingString:self.path];
    url = [url stringByAppendingString:[self securityParamForHeader]];
    return url;
}
- (NSString *)securityParamForHeader {
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    NSMutableDictionary *urlParamDict = [NSMutableDictionary dictionary];
    // default
    NSDictionary *dict = [self toDictionary];
    for (NSString *key in [dict allKeys]) {
        id value = [dict valueForKey:key];
        if (isEmpty(value) && [value isKindOfClass:[NSNull class]]) {
            continue;
        }
        
        if ([value isKindOfClass:[NSDictionary class]]) {
            [paramDict setValuesForKeysWithDictionary:value];
        }else{
            [paramDict setValue:value forKey:key];
        }
    }
//    [paramDict removeObjectForKey:@"apiKey"];
    //  apikey
    [urlParamDict setValue:@"6de9cc05-6c46-4e29-84f3-a638e442465a" forKey:@"apiKey"];

    // timestap

    // vision

    // system

    // model

    // log_channel
    
    // path
//    [paramDict setValue:self.path forKey:@"path"];
    // token
    // sign
    NSArray *keysArray = [paramDict allKeys];
    NSArray *sortedKeyArray = [keysArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    NSString *orderedStr = @"";
    for (NSString *key in sortedKeyArray) {
        id value = [paramDict valueForKey:key];
        NSString *param = [NSString stringWithFormat:@"%@=%@", key, value];
        orderedStr = [[orderedStr stringByAppendingString:param] stringByAppendingString:@"&"];
    }

    
    NSString *apendStr = @"?";
    for (NSString *key in urlParamDict) {
        apendStr = [apendStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", key, [urlParamDict valueForKey:key]]];
    }
    
    apendStr = [apendStr substringToIndex:apendStr.length - 1];
    
    return apendStr;
}
- (NSDictionary *)_paramDict {
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    NSDictionary *dict = [self toDictionary];
    for (NSString *key in [dict allKeys]) {
        id value = [dict valueForKey:key];
        if (isEmpty(value) && [value isKindOfClass:[NSNull class]]) {
            continue;
        }
        if ([value isKindOfClass:[NSDictionary class]]) {
            [paramDict setValuesForKeysWithDictionary:value];
        }else{
            [paramDict setValue:value forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:paramDict];
}

// 约定server返回的业务逻辑错误为非负整数
- (void)dealWithResponseJson:(NSString *)json
{
    // 解码对象不存在，直接返回json数据
    if (!_retClass || ![_retClass isSubclassOfClass:[JSONModel class]]) {
        _completeBlock(json, nil);
        return;
    }
    
    NSError *error = nil;
    EngineMannagerItem *item = [[_retClass alloc] initWithString:json error:&error];
    NSString *title = @"";
    // json格式错误
    if (error) {
        title = [NSString stringWithFormat:@"数据加载失败\n错误代码%@", item.code];
        error = [NSError errorWithDomain:error.domain code:-1 userInfo:@{NSLocalizedDescriptionKey:title}];
        _completeBlock(nil, error);
        NSLog(@"JSON Wrong -------> %@", error.localizedDescription);
        return;
    }
//
    if (item.code.integerValue == 301) { // 需要登录
//        BaseViewController *vc = [BaseViewController topViewController];
//        if ([vc isKindOfClass:[LoginOrRegViewController class]]) {
//            return;
//        }

//        [UserManager sharedInstance].loginStatus = NO;
//        [[NSNotificationCenter defaultCenter]postNotificationName:UserDidLogoutNotification object:nil];
//        [vc.navigationController popToRootViewControllerAnimated:YES];
//        [UserManager loginToInput];

//        [[BaseViewController topViewController] showToast:@"帐号已在其它设备登录"];
        title = [NSString stringWithFormat:@"%@\n错误代码%@", item.message, item.code];
        error = [NSError errorWithDomain:AFURLRequestSerializationErrorDomain code:error.code userInfo:@{NSLocalizedDescriptionKey:title}];
        _completeBlock(nil, error);
        return;
    }

    // 业务逻辑错误
//    if (item.code.integerValue != 200) {
//        title = [NSString stringWithFormat:@"%@\n错误代码%@", item.message.length==0? @"数据错误":item.message, item.code];
//        error = [NSError errorWithDomain:@"数据错误" code:-2 userInfo:@{NSLocalizedDescriptionKey:title}];
//        _completeBlock(item, error);
//        return;
//    }
    
    // 正常数据
    _completeBlock(item, nil);
}
@end


@implementation EngineMannagerItem
@end

@implementation EngineMannagerError
+ (JSONKeyMapper *)keyMapper {
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
                                                                  @"key" : @"name",
                                                                  }];
}
@end

